import 'dart:async';

import 'package:common_utils/common_utils.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:xinxuan/common/dialogs/del_dialog.dart';
import 'package:xinxuan/controllers/common_page_controller.dart';
import 'package:xinxuan/http/http_util_service.dart';
import 'package:xinxuan/vo/pay_verification_vo.dart';
import 'package:xinxuan/vo/system_bank_list_vo.dart';
import 'package:xinxuan/vo/verification_vo.dart';

class BankCardController extends GetxController {

  final CommonPageController commonPageController = Get.find();

  /// 姓名
  var accountName = ''.obs;
  /// 账号
  var cardNumber = ''.obs;
  /// 是否默认 0 否， 1 是
  var isDefault = 1.obs;
  /// 银行卡ID
  var bankId = 0.obs;
  /// 验证码
  var verificationCode = ''.obs;
  /// 系统银行卡列表
  var systemBankArr = <SystemBankItem>[].obs;
  /// 银行卡下拉选中项
  var scrollController = FixedExtentScrollController( initialItem: 0).obs;
  /// 选中的银行卡项
  var selectedBankItem = SystemBankItem().obs;
  /// 身份证号码
  var identityNumber = ''.obs;
  /// 银行卡ID （修改时使用）
  int id = 0;
  // /// 倒计时剩余时间
  var duration = 60.obs;
  /// 时间倒计时
  Timer? _timer;  
  /// 预保存银行卡ID
  int paymentId = 0;
  String verificationKey = '';

  @override
  void onReady() async {
    await getSystemBankList();
    if (Get.arguments != null) {
      Map<String, dynamic> argumentsMap = Get.arguments;
      if (Get.arguments != null && argumentsMap['data'] != null) {
        Map<String, dynamic> mapData = argumentsMap['data'];
        ininEditBank(mapData);
      }
    }
    super.onReady();
  }

  /// 获取系统银行卡列表
  getSystemBankList() async {
    SystemBankListVo systemBankListVo = await HttpUtilService.getSystemBankList();
    systemBankArr.value = systemBankListVo.data!;
  }

  /// 初始化修改数据
  ininEditBank(Map<String, dynamic> map) {
    id = map['id'];
    accountName.value = map['accountName'];
    cardNumber.value = map['cardNumber'];
    isDefault.value = map['isDefault'];
    bankId.value = map['bankId'];
    identityNumber.value = map['identityNumber'];
    verificationCode.value = '';
    verificationKey = '';
    if (systemBankArr.length > 0) {
      for (int i = 0; i < systemBankArr.length; i++) {
        if (bankId.value == systemBankArr[i].id) {
          scrollController.value = FixedExtentScrollController( initialItem: i);
          selectedBankItem.value = systemBankArr[i];
          break;
        }
      }
    } else {
      scrollController.value = FixedExtentScrollController( initialItem: 0);
      selectedBankItem.value = SystemBankItem();
    }
    update();
  }

  /// 添加银行卡
  addBankCard() async {
    if (!checkParam()) {
      return;
    }
    if (TextUtil.isEmpty(verificationCode.value)) {
      EasyLoading.showToast('请填写验证码');
      return;
    }
    if (paymentId <= 0) {
      return;
    }
    await HttpUtilService.addBankCard(
      paymentId: paymentId,
      isDefault: isDefault.value, 
      verificationCode: verificationCode.value,
      verificationKey: verificationKey
    );
    Get.back();
    EasyLoading.showToast('添加成功');
  }

  /// 修改选中银行卡
  changeBankIndex(int index) {
    scrollController.value = FixedExtentScrollController( initialItem: index);
  }

  /// 确定选中银行卡
  determineBank() {
    selectedBankItem.value = systemBankArr[scrollController.value.initialItem];
    bankId.value = selectedBankItem.value.id!;
    update();
  }

  /// 修改银行卡信息
  editBankCard() async {
    if (!checkParam()) {
      return;
    }
    if (TextUtil.isEmpty(verificationCode.value)) {
      EasyLoading.showToast('请填写验证码');
      return;
    }
    bool res = await HttpUtilService.editBankCard(
      id: id,
      accountName: accountName.value, 
      cardNumber: cardNumber.value, 
      isDefault: isDefault.value, 
      bankId: bankId.value, 
      verificationCode: verificationCode.value,
      identityNumber: identityNumber.value,
      verificationKey: verificationKey
    );
    if (res) {
      Get.back();
      EasyLoading.showToast('修改成功');
    }
  }

  /// 删除银行卡
  delBankCard() async {
    Get.dialog(DelDialog(message: '确定删除此银行卡吗？', onTap: () async {
      bool res = await HttpUtilService.delBankCard(id: id);
      if (res) {
        Get.back();
        EasyLoading.showToast('删除成功');
      }
    }));
  }

  /// 获取验证码
  getSmsCode() async {
    if (!checkParam()) {
      return;
    }
    PayVerificationVo res = await HttpUtilService.getPayVerification(
      type: 2, 
      accountName: accountName.value, 
      cardNumber: cardNumber.value,
      bankId: selectedBankItem.value.id!, 
      identityNumber: identityNumber.value, 
      mobile: commonPageController.userData.value.mobile!
    );
    if (res.data != null) {
      paymentId = res.data!.paymentId!;
      verificationKey = res.data!.verificationKey!;
      EasyLoading.showToast('发送成功');
      _timer?.cancel();
      _timer = Timer.periodic(Duration(seconds: 1), (timer) {
        duration.value--;
        if (duration.value == 0) {
          _timer?.cancel();
          duration.value = 60;
        }
      });
    }
  }

  /// 修改提现银行卡获取验证码
  geeEditReceivingBankSmsCode() async {
    if (!checkParam()) {
      return;
    }
    VerificationVo? res = await HttpUtilService.getVerificationCode(mobile: commonPageController.userData.value.mobile!, type: 'update_bank');
    if (res != null) {
      verificationKey = res.data!.verificationKey!;
      EasyLoading.showToast('发送成功');
      _timer?.cancel();
      _timer = Timer.periodic(Duration(seconds: 1), (timer) {
        duration.value--;
        if (duration.value == 0) {
          _timer?.cancel();
          duration.value = 60;
        }
      });
    }
  }

  /// 检查参数
  bool checkParam() {
    if (TextUtil.isEmpty(accountName.value)) {
      EasyLoading.showToast('请填写账号名');
      return false;
    }
    if (TextUtil.isEmpty(cardNumber.value)) {
      EasyLoading.showToast('请填写账号');
      return false;
    }
    if (bankId.value <= 0) {
      EasyLoading.showToast('请选择所属银行');
      return false;
    }
    if (!RegexUtil.isIDCard18Exact(identityNumber.value)) {
      EasyLoading.showToast('请填写正确身份证号');
      return false;
    }
    return true;
  }

  @override
  void onClose() {
    _timer?.cancel();
    super.onClose();
  }
}